package fitnesshub.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import fitnesshub.pojo.dto.AddConsumptionRecordDTO;
import fitnesshub.pojo.dto.ConsumptionRecordPageQueryDTO;
import fitnesshub.pojo.entity.ConsumptionRecord;
import fitnesshub.pojo.vo.MemberConsumptionRecordVO;
import fitnesshub.result.PageResult;
import fitnesshub.service.ConsumptionRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import fitnesshub.mapper.ConsumptionRecordMapper;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ConsumptionRecordServiceImpl implements ConsumptionRecordService {
    @Autowired
    private ConsumptionRecordMapper consumptionRecordMapper;
    @Override
    public PageResult page(ConsumptionRecordPageQueryDTO consumptionRecordPageQueryDTO) {
        PageHelper.startPage(consumptionRecordPageQueryDTO.getPage(), consumptionRecordPageQueryDTO.getPageSize());
        Page<ConsumptionRecord> page = consumptionRecordMapper.pageQuery(consumptionRecordPageQueryDTO);
        long total = page.getTotal();
        List<ConsumptionRecord> records = page.getResult();
        return new PageResult(total, records);
        //分页查询：查name为处，此时consumptionRecordPageQueryDTO对象的id=null，name=处，其他属性为null，page=1，pagesize=6是固定的，pageHelper会自动进行分页，得到1和6，其他的进入pageQuery里
    }

    /**
     * 添加消费记录
     * @param addConsumptionRecordDTO
     * @return
     */
    @Override
    public void addConsumptionRecord(AddConsumptionRecordDTO addConsumptionRecordDTO) {
        ConsumptionRecord consumptionRecord = new ConsumptionRecord();

        BeanUtils.copyProperties(addConsumptionRecordDTO, consumptionRecord);
        consumptionRecord.setConsumptionDate(LocalDateTime.now());

        consumptionRecordMapper.insert(consumptionRecord);
    }

    /**
     * 根据用户id查消费记录
     *
     * @param memberId
     * @return
     */
    @Override
    public List<MemberConsumptionRecordVO> getById(Integer memberId) {
        List<ConsumptionRecord> consumptionRecords = consumptionRecordMapper.getByMemberId(memberId);
        List<MemberConsumptionRecordVO> result = new ArrayList<>(consumptionRecords.size());

        for (ConsumptionRecord record : consumptionRecords) {
            MemberConsumptionRecordVO vo = new MemberConsumptionRecordVO();
            BeanUtils.copyProperties(record, vo);
            result.add(vo);
        }
        return result;
    }
}
